/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.caro.actions.transfer;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import org.caro.actions.listener.WaitingRoomListener;
import org.caro.utils.Constants;

/**
 *
 * @author TUAN ANH
 */
public class ControlGame extends Thread {

    private Socket socket; // socket 
    private ServerSocket serverSocket; // server
    private BufferedReader bufferedReader; // input stream
    private DataOutputStream dataOutputStream; // outputstream
    private int port;
    private String host;
    private int mode;
    private WaitingRoomListener waitingRoomListenner;

    public ControlGame(String host,int port,int mode,WaitingRoomListener waitingRoomListenner) {
    	super(String.valueOf(mode));
        this.host = host;
        this.port = port;
        this.mode = mode;
        this.waitingRoomListenner = waitingRoomListenner;
    }
    public ControlGame(String host,int port,int mode) {
        this.host = host;
        this.port = port;
        this.mode = mode;
    }
    
    @Override
	public void run() {
		try {
			initConnection();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    public String getIP(){
    	return this.host;
    }
	public void initConnection() throws Exception {
        try {
        	if (this.mode == Constants.HOST){
	            this.serverSocket = new ServerSocket(port);
	            this.socket = serverSocket.accept();
	            this.waitingRoomListenner.notify();
        	} else socket = new Socket(this.host,this.port);
            this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            this.dataOutputStream = new DataOutputStream(socket.getOutputStream());
        } catch (Exception ex) {
           	ex.printStackTrace();
           	close();
           	throw new Exception();
        }
    }

    public String receiveData() {
        String stringReceive = "";
        try {
            stringReceive = bufferedReader.readLine();
        } catch (Exception ex) {
            ex.printStackTrace();
            close();
        }
        return stringReceive;
    }

    public void sentData(String data) {
        try {
            for (int i = 0; i < data.length(); i++) {
                dataOutputStream.write((byte) data.charAt(i));
            }
            dataOutputStream.write(13);
            dataOutputStream.flush();
        } catch (Exception ex) {
        	close();
        }
    }

    public void close() {
        try {
            serverSocket.close();
            socket.close();
            bufferedReader.close();
            dataOutputStream.close();
        } catch (Exception ex) {
        }
    }
}
